import { defineStore, type StateTree } from "pinia";
interface Token {
  access_token: string
  token_type: string
  refresh_token: string
  expires_in: number
  user_id: string
}
export const useTokenStore = defineStore('mytoken', () => {
  const tokenJson = ref("")
  const userInfo = ref({})
  const token = computed<string>(() => {
    try {
      return tokenJson.value||window.localStorage.getItem("TokenInfo")||""
    } catch (error) {
      ElMessage.error("JSON字符串格式不合格");
      window.localStorage.setItem("TokenInfo","")
      throw error
    }
  })
  const user = computed<string>(() => {
    try {
      return JSON.stringify(userInfo.value)||window.localStorage.getItem("userInfo")||""
    } catch (error) {
      ElMessage.error("JSON字符串格式不合格");
      window.localStorage.setItem("userInfo","")
      throw error
    }
  })
  function saveToken(data:any) {
    window.localStorage.setItem("TokenInfo",data.accessToken);
    window.localStorage.setItem("userInfo",JSON.stringify(data.user));
    tokenJson.value = data.accessToken
    userInfo.value = data.user
  }
  function saveUser(data:any){
    userInfo.value = data.user
  }
  //校外暴露
  return { token,user,saveToken,saveUser }
})